import React, { useState, useEffect, Fragment } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import Store from 'electron-store';

import { Tabs, TabPanel, Input, Button, Checkbox, message, Form } from "tea-component";
import {DEFAULT_SDKAPPID, DEFAULT_SETTING_CONFIG } from '../../constants';
import timRenderInstance from '../../utils/timRenderInstance';
import { setIsLogInAction } from '../../store/actions/login';
import { changeFunctionTab } from '../../store/actions/ui';
import { setUserInfo } from '../../store/actions/user';
import { updateSettingConfig } from '../../store/actions/config';
import { initHistoryMessage } from '../../store/actions/message';
// eslint-disable-next-line import/no-unresolved
import { loginParam } from 'im_electron_sdk/dist/interfaces';
import { useSettingConfig } from '../../utils/react-use/useSettingConfig';
import { getApassConfig, loginSms, reloginSms, userVerifyByPicture } from '../../api';
import { ipcRenderer } from 'electron';
import { RENDERPROCESSCALL,GETDEVICETOKEN } from '../../../app/const/const';
import Toast from '../../components/toast/Toast';
import { aesDecry, aesEncry, setLoginIMtoprocess, sleep } from '../../utils/tools';
const store = new Store();
const request = require('request')
import path from 'path';
import os from 'os'

const tabs = [
    { id: 'passwordLogin', label: '用户登录' },
]

export const LoginContent = (): JSX.Element => {
    const autoLoginFromStore = store.get('autoLogin');
    const dispatch = useDispatch();
    const history = useHistory();
    const {userName,userPwd,serverlist,defaultser} = useSettingConfig();
    const [activedTab, setActivedTab] = useState('passwordLogin');
    const [isAutoLogin, setAutoLogin] = useState(!!autoLoginFromStore);
    const [username, setuserName] = useState(userName);
    const [userpwd, setuserPwd] = useState(userPwd);
    const [serlist,setserlist] = useState([]);
    const [phone, setphone] = useState('');
    const [cheidx, setCheIdx] = useState(0);
    //const isDisablelogin = (activedTab === 'passwordLogin' && userID && usersig) || (activedTab === 'verifyCodeLogin' && phone && captceh) || (activedTab === 'verifyCodeLogin' && smsLoginUserId && smsLoginToken);
    const [sessionId, setsessionId] = useState('')
    const [count, setcount] = useState(60)
    const [logining,setLogining] = useState(false);
    const [loginser,setLoginSer] =useState(defaultser);
    useEffect(() => {
        setuserName(userName);
        setuserPwd(userPwd);
    }, [userName,userPwd])

    const customizeTabBarRender = (children: JSX.Element) => {
        return <a className="customize-tab-bar">{children}</a>
    }

    const handleTabChange = ({ id }) => {
        // if(id === 'verifyCodeLogin') return message.warning({content: '敬请期待'});
        setActivedTab(id);
    }
    const handleLogin = () => {
        if (activedTab === 'passwordLogin') {
            handleLoginClick()
        }
        getDeviceToken()
    }
    const getDeviceToken =async () => {
        ipcRenderer.send(RENDERPROCESSCALL,{
            type: GETDEVICETOKEN,
        })   
    }
    const appId = aesDecry(DEFAULT_SDKAPPID);
    const handleImLogin = async (uid,usig)=>{
        const params: loginParam = {
            userID: uid,
            userSig: usig
        }
        setLoginIMtoprocess(uid);
        await ipcRenderer.invoke("re-create-main-instance", appId);
        dispatch(updateSettingConfig({sdkappId: appId,userId:uid,userSig: usig,
            userName:username, userPwd:userpwd }) );
        await sleep(800)  //dispatch通知初始化成功后才可以登陆，省略重新登陆直接卡死
        const  { code,  desc, json_param} = await timRenderInstance.TIMLogin(params);
        console.log(code, desc, json_param);
        setLogining(false)
        if (code === 0) {
            const storeKey = `${appId}-${uid}`;
            const catchedMessage = store.get(storeKey);
            if (catchedMessage) {
                const historyMessageMap = new Map(Object.entries(catchedMessage));
                dispatch(initHistoryMessage({
                    historyMessage: historyMessageMap
                }));
            }
            store.set('autoLogin', isAutoLogin);
            dispatch(setIsLogInAction(true));
            dispatch(setUserInfo({
                userId: uid,
                userSig: usig,
                userName:username,
                userPwd:userpwd
            }));
            store.set('setting-config', {
                sdkappId:appId,defaultser:Toast.defaultser,serverlist:serlist,
                userId: uid,userSig: usig,userName:username,userPwd:userpwd
            });
            document.title= username;
            setsessionId("")
            dispatch(changeFunctionTab('message'));
            history.replace('/home/message');
        }
        // @ts-ignore
        window.aegis.report("tim_login_secret")
    }
    const handleLoginClick = async () => {
        const deviceId = ipcRenderer.sendSync('get-device-id');
        Toast.deviceId=deviceId;
        if(loginser.length<1){
            message.warning({ style:{top:"50%"}, content: `系统检测中，稍后再试` })
            return;
        }
        setLogining(true)
        request.post(loginser+'/api/app/auth/login', {
            timeout:11000,
            json: {
                appVersion:"v1.1.0",
                clientType:"pc",
                clientSn:deviceId,
                username: username, //用户名
                password: userpwd, //密码
                type:1
            }
        }, (error, res, body) => {
            if (error) {
                setCheIdx(cheidx+1);
                setLoginSer(aesDecry( serlist[cheidx%serlist.length])) ;
                message.error({ style:{top:"50%"}, content: `连接错误：${error},请退出后再登陆` })
                setLogining(false)
                return
            }
            console.log(`statusCode: ${res.statusCode}-${loginser}`)
            //console.log(body);
            if(body.code==200){
                Toast.defaultser = loginser;
                Toast.muteStatus = body.data.muteStatus;
                Toast.token = body.data.token;
                Toast.downPath =  path.resolve(os.homedir(), 'download/'+body.data.imUserId);
                if(body.data.isNew && Toast?.serConfig?.open_def_group=="1"){
                    request.post(Toast.defaultser+'/api/app/member/editNickname',{
                        headers: {
                            Authorization: Toast.token,},           
                    },(error, res) => {
                        handleImLogin(body.data.imUserId,body.data.userSig);
                    });
                }else
                    handleImLogin(body.data.imUserId,body.data.userSig);
            }else if(body.code==12210){
                message.error({ style:{top:"50%"}, content: `登陆错误：${body.message},${username},请退出后再登陆` });
            }else{
                setCheIdx(cheidx+1);
                setLoginSer(aesDecry( serlist[cheidx%serlist.length])) ;
                message.error({ style:{top:"50%"}, content: `连接错误：${body.message},请退出后再登陆` })
            }
            setLogining(false)
        });    
    }
    const startCountDown = () => {
        const newCount = count - 1;
        const timmer = setTimeout(() => {
            setcount(newCount)
            clearTimeout(timmer)
        }, 1000)
    }
    useEffect(() => {
        if (sessionId && count < 60) {
            startCountDown()
        }
        if(count === 0){
            setcount(60)
            setsessionId("")
        }
        console.log("密码"+aesEncry("imsdkid"));
    }, [count])
    const captchaCallback = async (data) => {
        console.log(data)
        const { randstr, ticket, ret, appid } = data;
        if (ret === 0) {
            const response: any = await userVerifyByPicture({
                appId: appid,
                ticket,
                randstr,
                phone: `+86${phone}`
            })
            // console.log(response)
            const { data, errorCode, errorMessage } = response.data;
            if (errorCode === 0) {
                // 防水墙验证成功
                const { sessionId } = data;
                setsessionId(sessionId)
                // 开始倒计时
                startCountDown()
            } else {
                message.error({ style:{top:"50%"}, content: `出现错误:${errorMessage}` })
            }
        }
    }
    const getCaptch = () => {
        const phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (!phone || !phoneReg.test(phone)) {
            message.error({
                style:{top:"50%"},
                content: "请输入正确的手机号"
            })
            return
        }
        getConfig()
    }
    const getConfig = async () => {
        const config: any = await getApassConfig()
        // if(config.data){}
        const { errorCode, errorMessage, data } = config.data;
        if (errorCode === 0) {
            const { captcha_web_appid } = data
            // @ts-ignore
            const captcha = new TencentCaptcha(`${captcha_web_appid}`, captchaCallback, {});
            captcha.show()
        } else {
            message.error({
                style:{top:"50%"},
                content: `发生错误:${errorMessage}`
            })
        }
        // console.log(config.data.data)
    }
    const resetConfig = () => {
        store.delete("sms_relogin_token")
    }
    const  getSync=(url) =>{                //异步request操作转成promise
        const async = require('async');
        return new Promise((resolve, reject,) => {
          async.waterfall([
            function(callback) {
              request.get({url,timeout:5000}, callback);  //这里callback调用下一个函数
            },
            function(response, body, callback) {
              if (response.statusCode !== 200) {
                callback(`Request failed with ${response.statusCode}`);  //这里callback调用最后函数
              } else {
                callback(null, body);
              }
            }
          ], function(error, result) {
            if (error) {
              reject(error);
            } else {
              resolve(result);
            }
          });
        });
    }
    const checkServer =async (ischeckend:boolean=false,list:any=null)=>{
        //console.time("checkServer")
        let serslist =list? list: DEFAULT_SETTING_CONFIG.serverlist;
        for(let i=0;i<serslist.length;i++){
            const itemser =aesDecry(serslist[i]);
            try{
                const result= await getSync(itemser +'/api/app/sysConfig/getServeIpList') as string;
                setLoginSer(itemser);
                if(ischeckend) break;
                let body = JSON.parse(result);
                if(body.data?.serveIpList?.length>0){
                    //dispatch(updateSettingConfig({serverlist:body.data.serveIpList,defaultser:itemser}) );
                    setserlist(body.data.serveIpList);
                    console.log(body.data.serveIpList);
                    checkServer(true,body.data.serveIpList);
                }else{
                    dispatch(updateSettingConfig({defaultser:itemser}) );
                }
                break;
            }catch(ex){
                console.log(itemser+ ex);
            }
            console.log(Toast.defaultser);
        }
    }
    useEffect(() => {
        window.requestIdleCallback(() => {
            import(
                /* webpackPrefetch: true */
                /* webpackChunkName: "home" */
                '../home');
        })
        Toast.defaultser = "";
        Toast.token ="";
        checkServer();
    }, []);

    
    return (
        <div className="login--context" >
            <h2 className="login--context__title">登录</h2>
            <Tabs tabs={tabs} placement="top" activeId={activedTab} onActive={handleTabChange} tabBarRender={customizeTabBarRender}>
                <TabPanel id="passwordLogin">
                    <Input placeholder="请输入用户名" value={username} className="login--input" disabled={false} onChange={(val) => { setuserName(val) }} />
                    <Input placeholder="请输入用户密码" type="password"  value={userpwd} className="login--input" disabled={false} onChange={(val) => setuserPwd(val)} />
                </TabPanel>
            </Tabs>
            {/* <Checkbox display="block" onChange={hanldeAutoLogin} value={isAutoLogin} className="login--auto">
                下次自动登录
            </Checkbox> */}
            <Button type="primary" loading={logining} className="login--button" onClick={handleLogin} > 登 录</Button>
        </div>
    )
}